<!-- 面包屑 -->
<template>
  <!-- 固定个首页 -->
  <q-breadcrumbs-el label="首页" :to="{ path: '/' }" class="q-mx-md" :disable="route.path == '/'" />
  <!-- 路径导航 -->
  <q-breadcrumbs v-if="$q.screen.gt.xs" separator=" >> " class="text-grey-4" active-color="white">
    <q-breadcrumbs-el v-for="item in breadcrumbs" :key="item.label" v-bind="item" />
  </q-breadcrumbs>
</template>

<script lang="ts" setup>
  import { onBeforeMount, ref, watch } from 'vue';
  import { useRoute, RouteLocationRaw } from 'vue-router';

  type BreadcrumbsItem = { label: string; to: RouteLocationRaw; disable: boolean };

  const breadcrumbs = ref<BreadcrumbsItem[]>([]);

  const route = useRoute();
  const getBreadcrumb = () => {
    breadcrumbs.value = [];
    if (route.path === '/') return;

    let matched = route.matched.filter((item) => item.meta && item.meta.title);
    matched.forEach((item) => {
      if (item.meta?.breadcrumb !== false) {
        breadcrumbs.value.push({
          label: item.meta.title as string,
          to: item.name ? { name: item.name } : { path: item.path },
          disable: true,
        });
      }
    });
    if (breadcrumbs.value.length > 0) {
      breadcrumbs.value[breadcrumbs.value.length - 1].disable = true;
    }
  };
  // 页面加载或路由变化时重新计算面包屑
  onBeforeMount(() => {
    getBreadcrumb();
  });

  watch(
    () => route.path,
    (path) => {
      if (path.startsWith('/redirect/')) {
        return;
      }
      getBreadcrumb();
    },
  );
</script>
